var sysDictTable = function() {
	var validator;
	return {
		init : function() {
			util.initCheckBox("sys_dict_table");
			util.initCheckBox("editDict_table");
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'sys_dict_table\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';
			var checkBoxDivStrEdit = '<div class="checker" onclick="util.selectCheckBox(\'editDict_table\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';
			//查询字典信息列表
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "dictName",
					"value" : $("#id_dictName").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#sys_dict_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/sysDictIndex/getDictIndex.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						return checkBoxDivStr; 
					},
					"bSortable" : false
				},
				util.createRowIndex(),
				{
					"data" : "dictName",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "dictKey",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "remark",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"render" : function(data, type, full, meta) {
						 return '<a class="edit" data-type="editDict_table" data-toggle="modal">设置</a>';
					},
					"bSortable" : false
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected('sys_dict_table');
				}
			});
			
			//查询
			$("#btn_dict_query").click(function(e) {
				var table = $('#sys_dict_table').DataTable();
				table.draw(true);
			});
			//重置查询条件
			$("#btn_dict_reset").click(function(e) {
				$("#id_dictName").val("");
			});
			// 新增字典 打开弹窗  修改标题 清空表单内容
			$("#sys_dict_table_new").on('click',function(){
				$("#pkId").val('');
				$('#dict_add_title').text('新增字典');
				$('#add-dict').modal({show:true,keyboard:false});
			});
			
			//提交表单
			$(function(){
				$("#dict_add_save").click(function(){
					validator = validateMyForm("#dict_form");
					if(validator.form()){
						save();
					}else{
						return false;
					}
				})
			})
			
			
			/*
			 * 保存表单内容
			 */
			function save(){
				var d = {};
				d['pkId'] = $("#pkId").val();
				d['dictKey'] = $("#dictKey").val();
				d['dictName'] = $("#dictName").val();
				d['remark'] = $("#remark").val();
				var table = $('#sys_dict_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/sysDictIndex/saveOrUpdateDictIndex.mvc",
					"dataType" : "json",
					"async":false,
					"data" : d,
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#dict_add_cancel").click();
							table.draw(true);
						}else if(resp.msg=='DUPLICATE') {
							rmsBox.notify('error', {msg: '名称或编码已存在！',delay:3000});
							return;
						} else if(resp.msg=='FAILURE'){
							rmsBox.notify('error', {msg: '保存出错！',delay:3000});
							return;
						}
						
					}
				});
			}
			
			//关闭弹窗清空表单内容
			$("#dict_add_cancel").on("click", function(){
				$("#dict_form")[0].reset();
				if (validator) {
					validator.resetForm();
				}
			});
			
			// 修改
			$('#sys_dict_table_edit').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("sys_dict_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				$("#dict_add_title").text("编辑字典");
				var d = [];
				d = getDictById(util.getCheckedData("sys_dict_table")[0].pkId);
				$('#dictName').val(d.dictName);
				$('#dictKey').val(d.dictKey);
				$('#remark').val(d.remark);
				$("#pkId").val(d.pkId);
				$("#add-dict").modal({show:true,keyboard:false});
			});
			
			/**
			 * 
			 * @param 字典索引主键
			 */
			function getDictById(id){
				var data = [];
				$.ajax({
					"type" : "post",
					"url" : "main/sysDictIndex/getDictById.mvc",
					"dataType" : "json",
					"async": false, 
					"data" : {
						"pkId" : id
					},
					"success" : function(resp) {
						data = resp;
					}
				});
				return　data;
			}
			
			//删除字典索引
			//删除点击
			$("#sys_dict_table_del").on('click', function(){
				var d = [];
				d = util.getCheckedData("sys_dict_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中的记录？", "_confirmModal_yes");
				}
			});
			//确认删除
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("sys_dict_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#sys_dict_table').DataTable();
				var selRows = table.rows('.selected');
				$.ajax({
					"type" : "post",
					"url" : "main/sysDictIndex/delDictIndex.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if (resp.msg == 'FAILURE') {
							rmsBox.notify('error', {msg: '删除成功！',delay:3000});
						} else {
							rmsBox.notify('success', {msg: '删除成功！'});
							selRows.remove();
							table.draw(true);
						}
					}
				});
			});
			
			
			
			
			/************************************编辑字典值************************************/
			$('#sys_dict_table').on('click','a.edit', function(e) {
				var table = $('#sys_dict_table').DataTable();
				
				var row = table.cell($(this).parent()).index().row;
				var data = table.data()[row];
				var type = $(this).data("type");
				$("#editDictPanel").modal({show:true,keyboard:false});
				$("#editDict_table").DataTable().draw(true);
			});
			
			// 字典详情查询
			function queryDictData(sSource, aoData, fnCallback) {
				if(util.getCheckedData("sys_dict_table")==0){
					return;
				}
				aoData.push({
					"name" : "parentKey",
					"value" : util.getCheckedData("sys_dict_table")[0].dictKey
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
						
					}
				});
			};
			var edcitDictTable = $('#editDict_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/sysDict/getDict.mvc",
				"fnServerData" : queryDictData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						return checkBoxDivStrEdit; 
					},
					"bSortable" : false
				},
				util.createRowIndex(),
				{
					"data" : "dictValue",
					"bSortable" : false
				}, {
					"data" : "dictKey",
					"bSortable" : false
				}, {
					"data" : "dictSort",
					"bSortable" : false
				}, {
					"data" : "createUser",
					"bSortable" : false
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected('editDict_table');
				}
			});
			// 拼接新增行
			var checkBoxTrStr = '<td><div class="checker" onclick="util.selectCheckBox(\'editDict_table\', this)"><span><input type="checkbox" class=""></span></div></td>';

			var dictNewTrStr = '<tr class="newTr">'
				+ checkBoxTrStr
				+ '<td>1</td>'
				+ '<td><input id="new_dictValue" type="text" class="inputWidth" maxLength="32"></td>'
				+ '<td><input id="new_dictKey" type="text" class="inputWidth" maxLength="32"></td>'
				+ '<td><input id="new_dictSort" type="number" step="1" min="0" class="inputWidth" oninput="if(value.length>4)value=value.slice(0,4)"></td>'
				+ '<td></td>';
			
			
			//新增
			$("#editDict_new").click(function(){
				if($("#editDict_table tr.newTr").length == 0 && $("#editDict_table tr.editTr").length == 0){
					$("#editDict_table tbody tr:first").before(dictNewTrStr);
				}
				
			});
			
			//修改
			$('#editDict_edit').click(function(e) {
				if($("#editDict_table tr.newTr").length != 0 || $("#editDict_table tr.editTr").length != 0){
					return;
				}
				var dataArray = [];
				dataArray = util.getCheckedData("editDict_table");
				if (dataArray.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return;
				}
				var data = dataArray[0];
				var rowIndex = data.rowIndex;
				var tr = $("#editDict_table").find("tr").eq(rowIndex+1);
				$(tr).addClass("editTr");
				$($(tr).find("td").eq(2))[0].innerHTML='<input id="new_dictValue" type="text"  data-id="'+data.pkId+'" value="'+ data.dictValue+'" class="inputWidth" maxLength="32">';
				$($(tr).find("td").eq(3))[0].innerHTML='<input id="new_dictKey" type="text" value="'+ data.dictKey+'" class="inputWidth" maxLength="32">';
				$($(tr).find("td").eq(4))[0].innerHTML='<input id="new_dictSort" type="number" step="1" min="0" value="'+ data.dictSort+'" class="inputWidth" oninput="if(value.length>4)value=value.slice(0,4)">';
			});
			//保存
			$("#editDict_save").click(function(){
				if($("#editDict_table tr.editTr").length == 1){
					var dictValue = $("#new_dictValue").val();
					var dictKey = $("#new_dictKey").val();
					var dictSort = $("#new_dictSort").val();
					if (util.isEmpty(dictValue)) {
						rmsBox.notify('warning', {msg: '请输入字典Name！',delay:2000});
						return;
					}
					if (util.isEmpty(dictKey)) {
						rmsBox.notify('warning', {msg: '请输入字典Key！',delay:2000});
						return;
					}
					if (util.isEmpty(dictSort)) {
						rmsBox.notify('warning', {msg: '请输入排序！',delay:2000});
						return;
					}
					var obj = {};
					obj = { "pkId" : $("#new_dictValue").data("id") + '',
							"parentKey" : util.getCheckedData("sys_dict_table")[0].dictKey, 
							"dictValue" : dictValue,
							"dictKey": dictKey,
							"dictSort": dictSort
							};
					$.ajax({
						"type" : "post",
						"url" : "main/sysDict/saveOrUpdateDict.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"record" : JSON.stringify(obj)
						},
						"success" : function(resp) {
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#editDict_table").DataTable().draw(true);
						}
					});
				}
				if($("#editDict_table tr.newTr").length == 1){
					var dictValue = $("#new_dictValue").val();
					var dictKey = $("#new_dictKey").val();
					var dictSort = $("#new_dictSort").val();
					var flag = false;
					if (util.isEmpty(dictValue)) {
						rmsBox.notify('warning', {msg: '请选择字典显示值！',delay:2000});
						return;
					}
					if (util.isEmpty(dictKey)) {
						rmsBox.notify('warning', {msg: '请输入字典Key！',delay:2000});
						return;
					}
					if (util.isEmpty(dictSort)) {
						rmsBox.notify('warning', {msg: '请输入排序！',delay:2000});
						return;
					}
					var obj = {};
					obj = { "parentKey" : util.getCheckedData("sys_dict_table")[0].dictKey, 
							"dictValue" : dictValue, 
							"dictKey" : dictKey,
							"dictSort": dictSort,
							};
					$.ajax({
						"type" : "post",
						"url" : "main/sysDict/saveOrUpdateDict.mvc",
						"dataType" : "json",
						"data" : {
							"record" : JSON.stringify(obj)
						},
						"success" : function(resp) {
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#editDict_table").DataTable().draw(true);
						}
					});
				}
				
			});
			
			//删除点击
			$("#editDict_del").on('click', function(){
				var d = [];
				d = util.getCheckedData("editDict_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中的记录？", "delete_dict_detail_confirmModal");
				}
			});
			
			//确认删除
			$("#_confirmModal").on('click', '#delete_dict_detail_confirmModal', function() {
				var d = [];
				d = util.getCheckedData("editDict_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#editDict_table').DataTable();
				var selRows = table.rows('.selected');
				$.ajax({
					"type" : "post",
					"url" : "main/sysDict/delDict.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if (resp.msg == 'FAILURE') {
							rmsBox.notify('error', {msg: '删除出错！',delay:3000});
						} else {
							rmsBox.notify('success', {msg: '删除成功！'});
							selRows.remove();
							table.draw(true);
						}
					}
				});
			});
			
			//刷新
			$("#editDict_ref").click(function(){
				$("#editDict_table").DataTable().draw(true);
			});
			
			/*
			 * validate 自定义验证
			 */
			function validateMyForm(formId){
				return $(formId).validate({  
					errorElement: 'em',
					errorClass: 'redStar',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	dictName:'required',
			        	dictKey:'required',
			        	dictType:'required'
			           },  
			        messages:{  
			        	dictName:'不能为空',
			        	dictKey:'不能为空',
			            dictType:'不能为空'
			            }, 
			            
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });  
			}
			$(function(){
				$('.search-body input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_dict_query').click();
					}
				});
			});
		}
	};
}();